﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AspnetUtil.Web.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

namespace AspnetUtil.Web.Filter
{
    /// <summary>
    /// 验证请求参数
    /// </summary>
    public class ValidateFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var state = context.ModelState;
            if (state.IsValid)
            {
                await next();
            }
            else
            {
                var result = new ApiResult<object> {Code = (int) HttpStatusCode.BadRequest};
                var arr = (from s in state from err in s.Value.Errors select err.ErrorMessage).ToArray();
                result.Message = string.Join(" | ", arr);
                var response = context.HttpContext.Response;
                response.StatusCode = result.Code;
                await response.WriteAsJsonAsync(result);
            }
        }
    }
}